
/*
* 贷后管理首页 台账 js
*
* */
var layer;
var table;
var basePath;
var vm;
var templateCode = document.getElementById("templateCode").getAttribute("value");
var fileId = document.getElementById("fileId").getAttribute("value");
var batchCode = document.getElementById("batchCode").getAttribute("value");
var tableColum;
window.layinit(function (htConfig) {
    var _htConfig = htConfig;
    basePath = _htConfig.coreBasePath;
    uiBasePath = _htConfig.uiBasePath;
    vm = new Vue({
        el: '#app',
        data: {
            loading: false,
            exporting: false,//导出标志位
            searchForm: {
                tableName: ''  //表格名称

            },
         // 文件上传
            uploadSalaryModel:false,
            uploadSalarySetForm:{
            	timeYearMonth:'',
            	uploadType: '',
                templateCode:'',
                uploadSalaryFile:null,
                salaryFileType:'',
            },
            eidtForm:{
                value:'',
                fieldName:'',
                fileId:'',
                jobCode:'',
                batchCode:''
            },
            deleteForm: {
                tableName:'',
                params:[]
            },
            templateList:[],

            uploadSalarySetFormValidate:{
            	timeYearMonth: [
                    { required: true, message: '请选择时间'},
                ],
                templateCode: [
                    { required: true, message: '请选择模板'},
                ],
                uploadType: [
                    { required: true, message: '请选择导入方式'},
                ],
                uploadSalaryFile: [
                    { required: true, message: '请选择导入文件'},
                ]
            },
            errorDataLog:[],
            errorFlagList:[],
            fileId:'',
            templateCode:'',
            
            // 上传错误数据
            uploadErrorDataModel:false,
            uploadErrorFile:false,
        },

        methods: {
            //重载表格
            toLoading: function () {
                if (table == null) {
                    return;
                }
                var self = this;
                self.loading = true;
                table.reload('listTable', {
                    where: {

                        tableName: self.searchForm.tableName  //表格名称

                    }
                    , page: {
                        curr: 1 //重新从第 1 页开始
                    }
                });
            },

            toLoadingInitDataTable: function (obj) {
                console.log("==========>>>>>重载后数据",obj)
                if (table == null) {
                    return;
                }
                var self = this;
                self.loading = true;
                table.reload('initDataTable', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                });
            },
            toLoadingErrorInfoTable: function (fileId) {

                if (table == null) {
                    return;
                }
                var self = this;

                self.loading = true;
                table.reload('errorInfoTable', {
                    where:{
                      fileId:fileId
                    },
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                });
            },


            handleReset: function (name) { // 重置表单
                vm.searchForm.trailerStartDate = '';
                vm.searchForm.trailerEndDate = '';

                vm.searchForm.status = '';
                //var a=$("#trailerStartDate");
                //console.log(a);
                //alert(JSON.stringify(a));
                var tt = this.$refs[name];
                vm.toLoading();
            },
            ////  ----   单行操作界面显示  结束 -----------------
            clickExport: function () {//导出Excel表格

            },
            init: function () {
                var self = this;

                //使用layerUI的表格组件
                layui.use(['layer', 'table', 'ht_ajax', 'ht_auth', 'ht_config'], function () {
                    layer = layui.layer;
                    table = layui.table;
                    //执行渲染
                    table.render({
                        elem: '#listTable' //指定原始表格元素选择器（推荐id选择器）
                        , id: 'listTable'

                        , cols: [[
                             {field:'fileName', title: '表格名称',align: 'center'}
                            ,{field:'time', title: '时间', sort: true,align: 'center'}
                            ,{field:'importUserName', title: '上传人',align: 'center'}
                            ,{field:'lastUpdateTime', title: '上传时间',sort: true,align: 'center'}
                            ,{fixed:'right',title: '操作', align: 'center',toolbar:'#barTools'}
                        ]], //设置表头
                        url: basePath + 'dataImport/list',

                        page: true,
                        done: function (res, curr, count) {
                            //数据渲染完的回调。你可以借此做一些其它的操作
                            //如果是异步请求数据方式，res即为你接口返回的信息。
                            //如果是直接赋值的方式，res即为：{data: [], count: 99} data为当前页数据、count为数据总长度
                            self.loading = false;
                        }
                    });
                    table.on('tool(listTable)', function (obj) {
                        var selectedRowInfo = obj.data;
                        if(obj.event === 'dataInfo'){
                            var url="/dataImport/info?templateCode="+obj.data.templateCode;
                            self.showInfo(url,"数据详情");
                        }

                        if(obj.event === 'errorInfo'){
                            var url="/dataImport/info?templateCode="+obj.data.templateCode;
                            self.showInfo(url,"数据详情");
                            var templateCode = selectedRowInfo.templateCode;
                            var fileId = selectedRowInfo.fileId;
                            self.showInitData(templateCode,fileId);
                        }

                    });
                })
            },

            confirmData: function(fileId,jobCode){

                var self = this;

                var url = basePath + "salarySheet/confirmData?templateCode="+templateCode+"&fileId="+fileId+"&jobCode="+jobCode;
                $.ajax({
                    type: "GET",
                    url: url,
                    contentType: "application/json; charset=utf-8",
                    async: false,
                    dataType: "json",
                    success: function (result) {
                        console.log("结果：========",result);
                        if (result.returnCode == "0") {
                            layer.msg("操作成功~！");
                        }
                    }

                });

            },

            showInfo:function (url,tile) {

                var openIndex= layer.open({
                    type: 2,
                    area: ['95%', '95%'],
                    fixed: false,
                    maxmin: true,
                    title:tile,
                    content: url
                });
            },

            getTableColum:function (templateCode,queryType) {
                var self = this;

                var url = basePath + "salarySheet/getTableColum?templateCode="+templateCode+"&queryType="+queryType+"&batchCode="+batchCode;
                $.ajax({
                    type: "GET",
                    url: url,
                    contentType: "application/json; charset=utf-8",
                    async: false,
                    dataType: "json",
                    success: function (result) {
                        console.log("结果：========",result);
                        if (result.returnCode == "0") {
                            tableColum = result.data.data;
                            console.log(tableColum);
                        }
                    }

                });
            },
            showInitData:function (templateCode,fileId) {
                var self = this;
                self.getTableColum(templateCode,1);
                self.showErrorInfo(fileId);
                self.fileId = fileId;
                console.log("========>>>batchCode",batchCode);


                //使用layerUI的表格组件
                layui.use(['layer', 'table', 'ht_ajax', 'ht_auth', 'ht_config'], function () {
                    layer = layui.layer;
                    table = layui.table;
                    //执行渲染
                    table.render({
                        elem: '#initDataTable' //指定原始表格元素选择器（推荐id选择器）
                        , id: 'initDataTable'

                        , cols: [tableColum], //设置表头
                        url: basePath + 'salarySheet/getSalaryTableData',

                        page: true,
                        where:{
                            templateCode:templateCode,
                            fileId:fileId,
                            queryType:1
                        },
                        done: function (res, curr, count) {
                            //数据渲染完的回调。你可以借此做一些其它的操作
                            //如果是异步请求数据方式，res即为你接口返回的信息。
                            //如果是直接赋值的方式，res即为：{data: [], count: 99} data为当前页数据、count为数据总长度
                            console.log("+++++++++++++++++++++++++++++++reload会不会执行这里");
                            self.showErrorCss();

                            self.loading = false;
                        }
                    });

                    table.on('edit(initDataTable)', function(obj){ //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"
                        console.log(obj.value); //得到修改后的值
                        console.log(obj.field); //当前编辑的字段名
                        console.log(obj.data); //所在行的所有相关数据
                        console.log("=======>>>>>>>单元格修改属性",obj);
                        self.updataSalary(obj);
                    });
                    table.on('tool(initDataTable)', function (obj) {
                        console.log("===========",obj);
                        var selectedRowInfo = obj.data;
                        if(obj.event === 'delete'){
                            layer.confirm('真的删除么?', function(index){
                                self.deleteForm.params.push(obj.data);
                                self.deleteSalaryData();
                                layer.close(index);
                            });
                        }

                        if(obj.event === 'confirmData'){
                            console.log("selectedRowInfo",selectedRowInfo);
                            var jobCode = selectedRowInfo.job_code;
                            var fileId = selectedRowInfo.file_id;
                            layer.confirm('请认真核对数据是否正确', function(index){
                                self.confirmData(fileId,jobCode);
                                self.toLoadingInitDataTable();
                                layer.close(index);
                            });

                        }

                    });
                })
            },
            //导出错误数据
            expErrorData:function () {
                var url= basePath + 'salaryExcel/exportErrorData?fileId='+ fileId;
                window.open(url);
            },
            
            // ====================================================上传错误数据开始  ===================================================*/
            //上传更正数据页面
            uploadErrorData:function () {
            	 var self = this;
                 self.uploadErrorDataModel = true;
                 
            },
            
            // 获取上传错误文件对象
            beforeUpLoadErrorFile: function (file) {
                this.$refs.uploadError.clearFiles();
                this.uploadErrorFile = file;
            },
            
            // 移除文件的方法
            removeFile:function(file, fileList){
            	 this.uploadErrorFile = null;
            },
            // 提交错误数据
            subimtErrorData: function(){
            	var self = this ; 
            	if(!self.uploadErrorFile){
            		 self.$Message.error('请选择上传文件！');
                     return false;
                }
            
             var loadingIndex = layer.load();
           	 var url = basePath + "dataImport/uploadErrorFile";
                var formData = new FormData();
                formData.append('file', self.uploadErrorFile);
                formData.append('fileId', fileId);
                $.ajax({
                    type: "POST",
                    url: url,
                    data: formData,
                    contentType: false,
                    processData: false,
                    success: function (data) {
                        console.log("上传返回参数  ===========",data);
                        if (data.returnCode == "0000") {
                            self.processImport(loadingIndex, data.data);
                        }else{
                            layer.close(loadingIndex);
                            self.$Modal.error({content: '消息：' + data.msg});
                            self.toLoading();
                        }
                    },
                    error:function (data) {
                        layer.close(loadingIndex);
                        self.$Modal.error({content: '操作失败，消息：' + data});
                        self.toLoading();
                    }
                });
            	
            	
            },

            // 轮询请求后台
            processImport: function(loadingIndex, processCode){
                var self = this;
                
                var url = basePath + "salaryExcel/getUploadSalaryFileState?processCode=" + processCode;
                // 轮询
                var interval = setInterval(function(){
                    $.ajax({
                          type: "GET",
                          url: url ,
                          contentType: "application/json; charset=utf-8",
                          async: false,
                          dataType: "json",
                          success:function(data){
                                console.log("轮询结果", data);
                                if (data.returnCode == "0000") {
                                    layer.close(loadingIndex);
                                    clearInterval(interval);
                                    self.showInitData(templateCode, data.data);
                                    self.$refs.uploadError.clearFiles();
                                    self.uploadErrorDataModel = false;
                                    self.uploadErrorFile = null ;
                                    self.$Modal.success({
                                        title: '',
                                        content: '操作成功'
                                    });
                                 }else if(data.returnCode == "1"){
                                     // 不作处理
                                 }else if(data.returnCode == "9996"){
                                    // 轮询结束
                                    clearInterval(interval);
                                    layer.close(loadingIndex);
                                    self.showInitData(templateCode, data.data);
                                    self.$refs.uploadError.clearFiles();
                                    self.uploadErrorDataModel = false;
                                    self.uploadErrorFile = null ;
                                    self.$Modal.error({content: '消息：' + data.msg});
                                 }else{
                                    // 轮询结束
                                    clearInterval(interval);
                                    layer.close(loadingIndex);
                                    self.showInitData(templateCode, data.data);
                                    self.$refs.uploadError.clearFiles();
                                    self.uploadErrorDataModel = false;
                                    self.uploadErrorFile = null ;
                                    self.$Modal.error({content: '消息：' + data.msg});
                                 }
                            },
                            error:function (data) {
                                console.log("错误轮询", arguments);
                                // 轮询结束
                                clearInterval(interval);
                                layer.close(loadingIndex);
                                self.$refs.uploadError.clearFiles();
                                self.uploadErrorDataModel = false;
                                self.uploadErrorFile = null ;
                                self.$Modal.error({content: '消息：' + data.msg});
                            }
                          })
                  }, 2000);
            },


            // 取消上传窗口
            cancelErrorData:function(){
            	var self = this ; 
            	self.$refs.uploadError.clearFiles();
            	self.uploadErrorDataModel = false;
            	self.uploadErrorFile = null ;
            },
            // ====================================================上传错误数据结束  ===================================================*/
            //展示错误信息列表
            showErrorInfo:function (fileId) {
                var self = this;
                //使用layerUI的表格组件
                layui.use(['layer', 'table', 'ht_ajax', 'ht_auth', 'ht_config'], function () {
                    layer = layui.layer;
                    table = layui.table;
                    //执行渲染
                    table.render({
                        elem: '#errorInfoTable' //指定原始表格元素选择器（推荐id选择器）
                        , id: 'errorInfoTable'

                        , cols: [[
                            {field: 'jobCode', title: '工号', width:400}
                            ,{field: 'msg', title: '错误类型', width:400}
                            ,{field: 'content', title: '错误详情', width:400}
                        ]], //设置表头
                        url: basePath + "dataImport/error",
                        where:{
                          fileId:fileId
                        },
                        page: true,
                        done: function (res, curr, count) {
                            //数据渲染完的回调。你可以借此做一些其它的操作
                            //如果是异步请求数据方式，res即为你接口返回的信息。
                            //如果是直接赋值的方式，res即为：{data: [], count: 99} data为当前页数据、count为数据总长度
                            self.errorDataLog = res.data;
                            self.errorFlagList = [];
                            layui.each(self.errorDataLog,function (index,item) {
                                var dictCode = item.dictCode+"";
                                var jobCode = item.jobCode+"";
                                var fileAndJobCode = dictCode.trim()+jobCode.trim();
                                self.errorFlagList.push(fileAndJobCode);
                            });
                            self.loading = false;
                        }
                    });
                })
            },
            dataCheck:function () {
                var self = this;
                var fileId = document.getElementById("fileId").getAttribute("value");
                var batchCode = document.getElementById("batchCode").getAttribute("value");
                var url = basePath + "dataImport/checkImportData?fileId="+fileId+"&batchCode="+batchCode;
                $.ajax({
                    type: "GET",
                    url: url,
                    contentType: "application/json; charset=utf-8",
                    async: false,
                    dataType: "json",
                    success: function (result) {
                        console.log("结果：========",result);
                        if (result.returnCode == "0") {
                            //修改审核状态
                            self.updataCheckState(fileId,batchCode);
                            layer.msg("审核成功",{icon:1,shade: [0.8, '#393D49'],time:2000});
                        }else {

                        }
                    },
                    error:function () {
                        
                    }
                });
            },
            updataCheckState:function (fileId,batchCode) {
                var self = this;
                var url = basePath + "dataImport/updataCheckState?fileId="+fileId+"&batchCode="+batchCode;
                $.ajax({
                    type: "GET",
                    url: url,
                    contentType: "application/json; charset=utf-8",
                    async: false,
                    dataType: "json",
                    success: function (result) {
                        console.log("结果：========",result);
                        if (result.returnCode == "0") {
                            //修改审核状态

                        }else {

                        }
                    },
                    error:function () {

                    }
                });
            },
            // 校验单元格姓名及邮箱类型
            updataSalary:function(obj){
            	var value = obj.value //得到修改后的值
                ,data = obj.data //得到所在行所有键值
                ,field = obj.field; //得到字段
	            var self = this;
	            self.eidtForm.value=value;
	            self.eidtForm.fieldName=field;
	            self.eidtForm.fileId=data.file_id;
	            self.eidtForm.jobCode=data.job_code;
	            self.eidtForm.batchCode=data.batch_code;
	            var url = basePath + "salarySheet/validateUpdataSalary";
	
	            var data = JSON.stringify(self.eidtForm);
	            $.ajax({
	                type: "POST",
	                url: url,
	                contentType: "application/json; charset=utf-8",
	                async: false,
	                data:data ,
	                dataType: "json",
	                success: function (result) {
	                    console.log("结果：========",result);
	                    if (result.returnCode == "0") {
	                       self.updataSalaryExt(obj);
	                    }else if(result.returnCode == "9996"){
	                    	layer.confirm(result.msg, {
	                    		btn: ['确认', '取消'] //可以无限个按钮
	                    		}, function(index, layero){
	                    		   self.updataSalaryExt(obj);
	                    		}, function(index){
	                    			self.toLoadingInitDataTable();
	                                self.toLoadingErrorInfoTable(self.eidtForm.fileId);
	                                self.showErrorCss();
	                    		});
	                    }else{
	                    	 layer.msg(result.msg);
	                         self.toLoadingInitDataTable();
	                         self.toLoadingErrorInfoTable(self.eidtForm.fileId);
	                         self.showErrorCss();
	                    }
	                },
	                error:function (result) {
	                    layer.msg("更新失败："+result.msg);
	                }
	
	            });
            },
            
            //单元格更新
            updataSalaryExt:function (obj) {
                var value = obj.value //得到修改后的值
                    ,data = obj.data //得到所在行所有键值
                    ,field = obj.field; //得到字段
                var self = this;
                self.eidtForm.value=value;
                self.eidtForm.fieldName=field;
                self.eidtForm.fileId=data.file_id;
                self.eidtForm.jobCode=data.job_code;
                self.eidtForm.batchCode=data.batch_code;
                var url = basePath + "salarySheet/updataSalary";

                var data = JSON.stringify(self.eidtForm);
                console.log("data========>>>>>>",data);
                $.ajax({
                    type: "POST",
                    url: url,
                    contentType: "application/json; charset=utf-8",
                    async: false,
                    data:data ,
                    dataType: "json",
                    success: function (result) {
                        console.log("结果：========",result);
                        if (result.returnCode == "0") {
                            console.log("动态表名==========",result.data);
                            layer.msg("更新成功");
                            self.toLoadingInitDataTable();
                            self.toLoadingErrorInfoTable(self.eidtForm.fileId);
                            self.showErrorCss();
                        }else {
                            layer.msg(result.msg);
                            self.toLoadingInitDataTable();
                            self.toLoadingErrorInfoTable(self.eidtForm.fileId);
                            self.showErrorCss();
                        }
                    },
                    error:function (result) {
                        layer.msg("更新成功失败："+result.msg);
                    }

                });

            },
            //删除
            deleteSalaryData:function () {
                var self = this;
                var url = basePath + "salarySheet/deleteSalaryData";

                var data = JSON.stringify(self.deleteForm);
                console.log("data========>>>>>>",data);
                $.ajax({
                    type: "POST",
                    url: url,
                    contentType: "application/json; charset=utf-8",
                    async: false,
                    data:data ,
                    dataType: "json",
                    success: function (result) {
                        console.log("结果：========",result);
                        if (result.returnCode == "0") {
                            self.toLoadingInitDataTable();
                        }else {
                            vm.$Message.error('接口调用异常!');
                        }

                    },
                    error:function (result) {
                        vm.$Message.error('接口调用异常!');
                    }

                });
            },
            //多条删除
            deleteAll: function () {
                var self = this;
                var checkStatus = table.checkStatus('initDataTable');
                if (checkStatus.data.length == 0) {
                    layer.open({
                        title: '警告'
                        , content: '请勾选数据'
                    });
                    return;
                }
                layer.confirm('真的删除么?', function (index) {
                    self.deleteForm.params = checkStatus.data;
                    self.deleteSalaryData();
                    layer.close(index);
                });

            },
            showErrorCss:function () {
                var self = this;
                var errorData = self.errorFlagList;
                $(".layui-table-body.layui-table-main tr td").each(function () {

                    var field = $(this)[0].dataset.field+"";
                    var jobCode = $(this).parent().first()[0].childNodes[2].innerText+"";
//                    console.log("===========>>>>>>>>childNodes",$(this).parent().first()[0].childNodes);
                    var errorStr = field.trim()+jobCode.trim();

                    for(var i=0;i<errorData.length;i++){
                        if(errorStr === errorData[i]){
                            $(this).css({color: 'red', 'font-weight':"bold", 'font-size': '20px'})
                        }
                    }

                    var logData = self.errorDataLog;

                    $(this).hover(function (obj) {
                        var fileId = obj.currentTarget.dataset.field+"";
                        var jobCode = $(this).parent().first()[0].childNodes[2].innerText+"";
                        for(var i=0;i<logData.length;i++){
                            if(logData[i].dictCode == fileId.trim() && logData[i].jobCode == jobCode.trim() ){
                                layer.tips(logData[i].content, this, {
                                    tips: [1, '#3595CC']
                                });
                            }
                        }
                    });


                });
            }
            
        },

        mounted:function(){
            this.showInitData(templateCode,fileId);
        }
    });
});
//














